24. Renaming Files
Renaming Files
INSTRUCTOR NOTE:
Helpful Links
1) How to use for loops in Python
2) How to use the translate function in Python
More information on the string function translate
Let us understand the documentation for string.translate
In the python documentation for string translate, you will see
string.translate(s, table[, deletechars])
Notice that there are three argments (or inputs to the
function), s, table, and the optional deletechars (we know it's
optional because it's in square brackets). But only two are shown in
the video: table and deletechars. Don't worry, this will be
explained later. For now, learn this little trick, doing this:
import string
string.translate(file_name,None,'0123456789')
is equivalent to doing this (putting file_name
out front, in place of the string
module):
file_name.translate(None,'0123456789')
Python 3 Note
String translation changed in the transition from Python 2.7 to Python 3. The translation table is now separate from the translate()
function itself. To do this kind of translation in Python 3, you will need to create a translation table, and pass that into the translate()
function:
translation_table = str.maketrans("0123456789", " ", "0123456789")
filename.translate(translation_table)
You can read more about these changes in the documentation.